<template>
  <div>
    <el-row class="nav">
      <span class="font-weight">工单模板</span>
    </el-row>
    <el-divider></el-divider>
    <el-form :inline="true"
             class="coverage-style-searchForm">
      <el-form-item>
        <div class="demo-input-suffix">
          <el-input prefix-icon="el-icon-search"
                    clearable
                    placeholder="请输入模板名称"
                    v-model="core"></el-input>
        </div>
      </el-form-item>
      <el-form-item>
        <button @click="handleSearch"
                type="button"
                class="el-button el-button--primary el-button--medium h30Btn ">查询</button>
      </el-form-item>
      <el-form-item class="fr">
        <button @click="createForm({name:'新建工单模板'})"
                type="button"
                class="el-button el-button--primary el-button--medium h30Btn ">新建工单模板</button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-table class="table-td"
                ref="multipleTable"
                stripe
                border
                :header-cell-style="{background:'#F2F3F8'}"
                :data="tableData"
                v-loading="loading"
                tooltip-effect="dark"
                style="width:100%"
                @select="pinSelect"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection"
                         align="center"
                         min-width="10%"></el-table-column>
        <el-table-column label="工单模板名称"
                         align="center"
                         min-width="20%">
          <template slot-scope="scope">
            <span style="color: #2393f1">{{scope.row.name}}</span>
          </template>
        </el-table-column>
        <el-table-column label="最近修改时间"
                         align="center"
                         min-width="20%">
          <template slot-scope="scope">{{timestampToTime(scope.row.lastUpdateTime)}}</template>
        </el-table-column>
        <el-table-column prop="lastUserName"
                         label="最近修改人"
                         align="center"
                         min-width="20%"></el-table-column>
        <el-table-column label="操作"
                         align="center"
                         min-width="30%"
                         show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button icon="el-icon-delete"
                       type="text"
                       size="mini"
                       class="btn"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button icon="el-icon-edit"
                       type="text"
                       size="mini"
                       class="btn"
                       @click="handleEdit(scope.$index, scope.row, {name:'编辑工单模板'})">编辑</el-button>
            <el-button type="text"
                       size="mini"
                       class="btn"
                       icon="el-icon-document-copy"
                       @click="handleCopy(scope.$index, scope.row, {name:'复制工单模板'})">
              复制
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="paging-foot page-foot-spacing"
            :gutter="20">
      <el-col :span="12">
        <span class="color-select">批量操作</span>
        <span class="select-number">（已选中{{selectAllIdLength}}条）</span>
        <button @click="deleteBatch"
                type="button"
                class="el-button el-button--primary el-button--medium h30Btn ">删除</button>
      </el-col>
      <el-col :span="12">
        <div>
          <el-pagination background
                         class="el-pagination-style"
                         v-show="totalDataLength > 0"
                         @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page="page"
                         :page-sizes="[10, 20, 50, 100]"
                         :page-size="pageSize"
                         layout="total, sizes, prev, pager, next, jumper"
                         :total="totalDataLength"></el-pagination>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { selectContentById, copyById, selectByName, deleteBatch, deleteForm } from '@/api/formWork.js'
import common from '@/common/common.js'
export default {
  data () {
    return {
      lists: [],
      changeLists: [],
      origin: -1,
      pin: false,
      tableData: [],
      multipleSelection: [],
      core: '',
      page: 1,
      pageSize: 10,
      totalDataLength: 0,
      loading: true,
      selectAllId: [],
      selectAllIdLength: 0,
      handleTitText: ['新建工单模板', '编辑工单模板', '复制工单模板']
    }
  },
  created () {
    this.handleSearch()
  },
  watch: {
    selectAllId (newVal, oldVal) {
      this.selectAllId = newVal
    }
  },
  mounted () {
    // this.getSelectAll()
    window.addEventListener('keydown', code => { // 这个是获取键盘按住事件
      // console.log(code) // 这个是你按住键盘打印出键盘信息，在浏览器中自行查看
      if (code.keyCode === 16 && code.shiftKey) { // 判断是否按住shift键，是就把pin赋值为true
        this.pin = true
      }
    })
    window.addEventListener('keyup', code => { // 这个是获取键盘松开事件
      if (code.keyCode === 16) { // 判断是否松开shift键，是就把pin赋值为false
        this.pin = false
        if (this.lists.length > 2) {
          this.selectAllId = this.lists
        } else {
          this.selectAllId = this.changeLists
        }
        this.selectAllIdLength = this.selectAllId.length
      }
    })
  },
  destroyed () {
    window.removeEventListener('keydown', code => {
      if (code.keyCode === 16 && code.shiftKey) {
        this.pin = true
      }
    }, false)
    window.removeEventListener('keyup', code => {
      if (code.keyCode === 16) {
        this.pin = false
      }
    }, false)
  },
  methods: {
    pinSelect (item, row) {
      const data = this.tableData // 获取所有数据
      const origin = this.origin // 起点数 从-1开始
      const endIdx = row.index // 终点数
      if (this.pin && item.includes(data[origin])) { // 判断按住
        // this.$refs.multipleTable.selectClear()
        const sum = Math.abs(origin - endIdx) + 1// 这里记录终点
        const min = Math.min(origin, endIdx)// 这里记录起点
        var i = 0

        while (i < sum) {
          const index = min + i
          this.$refs.multipleTable.toggleRowSelection(data[index], true)
          i++
        }
        this.lists = this.selectAllId
      } else {
        this.origin = row.index // 没按住记录起点或没选起点
      }
    },
    handleSizeChange (pageSize) {
      this.pageSize = pageSize
      this.page = 1
      // this.getSelectAll()
      this.handleSearch()
    },
    handleCurrentChange (page) {
      this.page = page
      // this.getSelectAll()
      this.handleSearchData()
    },
    // 编辑
    handleEdit (index, row, params) {
      sessionStorage.setItem('customField', JSON.stringify(''))
      this.$store.commit('systemConfigTitFun', params)
      selectContentById(row.id).then(res => {
        if (res.data.retCode === 200) {
          let formData = {
            type: 1,
            option: 2,
            widgetForm: res.data.data.content,
            formName: res.data.data.name
          }
          sessionStorage.setItem('formData', JSON.stringify(formData))
          this
            .$store
            .commit('formWorkFun', row.id)
          this
            .$router
            .push('/makeForm')
        } else {
          this.$message({ message: res.data.msg, type: 'error' })
        }
      })
    },
    // 删除
    handleDelete (index, row) {
      this.deleteSelect([row.id])
    },
    // 新建
    createForm (params) {
      sessionStorage.setItem('customField', JSON.stringify(''))
      this
        .$store
        .commit('systemConfigTitFun', params)
      this
        .$store
        .commit('formWorkFun', '')
      let formData = {
        type: 1,
        option: 1,
        widgetForm: []
      }
      sessionStorage.setItem('formData', JSON.stringify(formData))

      this
        .$router
        .push('/makeForm')
    },
    // 复制
    handleCopy (index, row, params) {
      this
        .$store
        .commit('systemConfigTitFun', params)
      copyById(row.id).then(res => {
        let formData = {
          type: 1,
          option: 3,
          widgetForm: res.data.data.content,
          formName: res.data.data.name
        }
        sessionStorage.setItem('formData', JSON.stringify(formData))
        this
          .$store
          .commit('formWorkFun', '')
        this
          .$router
          .push('/makeForm')
      })
    },
    // 搜索
    handleSearch () {
      this.page = 1
      this.handleSearchData()
    },
    // 搜索封装
    handleSearchData () {
      let params = {
        name: this.core,
        currentPage: this.page,
        pageSize: this.pageSize
      }
      selectByName(params).then(res => {
        let data = res.data
        if (data.retCode === 200) {
          this.tableData = data.data.list
          this.totalDataLength = data.data.total
          this.loading = false
          if (data.data.length <= 0) {
            this.page = this.page - 1
            this.handleSearchData()
          }
          this.tableData.forEach((item, index) => {// 遍历索引,赋值给data数据
            item.index = index
          })
        }
      })
    },
    toggleSelection (rows) {
      if (rows) {
        rows.forEach(row => {
          this
            .$refs
            .multipleTable
            .toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange (val) {
      this.selectAllIdLength = val.length
      this.selectAllId = []
      val.map((value, key, index) => {
        this.selectAllId.push(value.id)
      })
      this.changeLists = this.selectAllId
    },
    deleteBatch () {
      if (this.selectAllIdLength === 0) {
        this.$message({ message: '请选择删除项', type: 'error' })
        return
      }
      this.deleteSelect(this.selectAllId)
    },
    deleteSelect (idList) {
      this
        .$confirm('确认要删除吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          center: true,
          customClass: 'messageBox-prompt-delete'
        })
        .then(() => {
          deleteBatch(idList).then(res => {
            if (res.data.retCode === 200) {
              this.$message({ message: res.data.msg, type: 'success' })
              // this.getSelectAll()
              // this.handleSearch()
              this.handleSearchData()
            } else {
              this.$message({ message: res.data.msg, type: 'error' })
            }
          })
        })
    },
    // 时间戳的转换
    timestampToTime (timestamp) {
      return common.timestampToTime(timestamp)
    }
  }
}
</script>
<style scoped>
/*  */
.title {
  padding: 12px 20px;
  float: left;
  color: #b50029;
}

.color-select {
  font-size: 13px;
  padding: 0 5px;
}

.select-number {
  color: #b50029;
  font-size: 13px;
  padding: 0 5px;
}

.coverage-style-searchForm > .el-input__inner {
  width: 300px;
}

.el-pagination {
  text-align: right;
}

> .btn > i {
  font-size: 13px;
  margin-right: 10px;
}

.copy-img-sign {
  float: left;
  width: 16px;
  height: 16px;
  margin-right: 10px;
}

> .el-input__icon {
  font-size: 13px;
  font-weight: 800;
}
</style>